#/usr/bin/env python

import os
import re
import json
import urllib2

file_ios_path = './scripts/last_commit_id.txt';
url = 'https://oapi.dingtalk.com/robot/send?access_token=3868cb700e1f80fbce9e989f404ce9f7dc040f7c0fbd5e304dc9e950fd7b4843'
path = os.getcwd()

def ding_talk_send_message(filter_logs, file_path):
	content = '\n'.join(filter_logs)
	persons = [{
		'name': 'zz',
		'phone': 18180983359
	}]

	atMobiles = []
	for person in persons:
		if person['name'] in content:	
			atMobiles.append(person['phone'])

	parameters = {
		"msgtype": 'text',
		"text": {
			"content": content
		},
		"at": {
			"atMobiles": atMobiles
		}
	}
	req = urllib2.Request(url)
	req.add_header("Content-Type", "application/json; charset=utf-8")
	opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
	response = opener.open(req, json.dumps(parameters))
	write_last_commit_id(file_path)
	return response.read()

def is_important_log(log):
	important_tags = ["# ", '#\t', '#[0-9]{1,}']
	for tag in important_tags:
		if re.search(tag, log):
			return 1 
	return 0

def filter_logs(logs):
	filter_logs = filter(is_important_log, logs)
	return filter_logs

def get_current_author():
	return os.popen('git config --get user.name').read().replace('\n', '').replace(' ', '_')

def get_git_log(current_author, last_commit_id):
	print('path is ', os.getcwd())
	print('git log --pretty=format:"%an: %s" --author=' + current_author + ' ' + last_commit_id + '...HEAD')
	logs = os.popen('git log --pretty=format:"%an: %s" --author=' + current_author + ' ' + last_commit_id + '...HEAD').read().split('\n')
	return filter_logs(logs)

def write_last_commit_id(file_path):
	last_commit_id = os.popen('git rev-parse --short HEAD').read().replace('\n', '')
	with open(file_path, 'w+') as f:
		f.write(last_commit_id)
	print(file_path, 'write end')

def read_last_commit_id(file_path):
	if os.path.exists(file_path):
		with open(file_path, 'r') as f:
			last_commit_id = f.read().replace('\n', '')
			author = get_current_author()
			logs = get_git_log(author, last_commit_id)
			if len(logs) != 0:
				ding_talk_send_message(logs, file_path)

	else:
		write_last_commit_id(file_path)

def main():
	branch = os.popen('git rev-parse --abbrev-ref HEAD').read().replace('\n', '')
	if branch != 'develop':
		print('Your branch is not in develop, current branch is ' + branch)
		exit(0)
	
	read_last_commit_id(file_ios_path)
	

if __name__ == '__main__':
	main()